const http = require("http");
const url = require("url");
const querystring = require("querystring");

function startServer(handle, router) {
  var server = http.createServer((request, response) => {
    // router(handle, request.url, response);
    var pathname = url.parse(request.url).pathname;
    var data = [];

    request.on("error", (err) => {
      console.log(err);
    }).on("data", (chunk) => {
      data.push(chunk)
    }).on("end", function () {
      if (request.method == "POST") {
        // post请求
        data = Buffer.concat(data).toString();
        router(handle, pathname, response, querystring.parse(data))
      } else {
        // get请求
        var param = url.parse(request.url).query;
        router(handle, pathname, response, param);
      }
    })
  })

  server.listen(3127, "127.0.0.1");
  console.log("服务器已经运行在3127端口上");
}

module.exports = {
  startServer
}